import message from "@/store/message";
import {get_chatting_user_list, get_singleton_chatting_user, count_all_un_read} from "@/api/conversation"
import { formatDate } from "@/utils/d_times"
import { removeDuplicates } from "@/utils/d_fun"
import {ElMessage} from "element-plus";
export default {
  namespaced: true,
  state: {
    active: null,
    list: [],
    pageNum: 1,
    pageSize: 30,
    total: 0,
    scrollbarTop: 0,
    countAllRead: 0
  },
  getters: {
    conversations: state => {
      return state.list
    }
  },
  mutations: {
    UPDATE_COUNT_ALL_READ: (state, data) => {
      state.countAllRead = data
    },
    SET_CONVERSATION: (state, data) => {
      state.list = removeDuplicates([...state.list, ...data.list])
      state.total = data.total
      if(data.list.length) {
        state.pageNum++
      }else if(state.pageNum > 1) {
        ElMessage.warning("没有更多会话")
      }
    },
    SET_ACTIVE: (state, id) => {
      state.active = null
      for (let i = 0; i < state.list.length; i++) {
        const item = state.list[i]
        if(item.id === id) {
          state.active = {
            conversationId: item.id,
            ...item.from,
            accountName: item.to.nickName,
            accountId: item.to.id
          }
          state.countAllRead -= item.unReadCount
          item.unReadCount = 0
          break
        }
      }
    },
    UPDATE_CONVERSATION_PRIVATE_MESSAGE:(state, message) => {
      let obj
      for (let i = 0; i < state.list.length; i++) {
        const item = state.list[i]
        if(item.id == message.msgConversationId) {
          if(item.to.id == message.from) {
            state.countAllRead -= item.unReadCount
            item.unReadCount = 0
          }else {
            item.unReadCount += 1
            state.countAllRead += 1
          }
          obj = item
          state.list.splice(i, 1)
        }
      }
      obj.message = {
        content: message.content,
        createTime: message.createTime,
        createTimeAt: formatDate(message.createTime),
        from: message.from,
        id: message.id,
        to: message.to,
        type: message.type,
      }
      state.list.unshift(obj)
    },
    ADD_CONVERSATION_PRIVATE_MESSAGE:(state, obj) => {
      if(state.list.length > 500) {
        state.list.splice(state.list.length - 1, 1)
      }
      if(obj.push){
        state.list.push(obj.data)
      }else {
        state.list.unshift(obj.data)
      }
    },
    CLOSE_MESSAGE: (state) => {
      state.active = null
    },
    SET_SCROLLBAR_TOP:(state, val) => {
      state.scrollbarTop = val
    }
  },
  actions: {
    /**
     * 设置滚动条
     * @param commit
     * @param val
     */
    setScrollbarTop({commit}, val){
      commit("SET_SCROLLBAR_TOP", val)
    },
    /**
     * 获取会话列表
     * @param commit
     * @returns {Promise<string>}
     */
    async getConversations({commit, state}, init) {
      if(init){
        state.pageNum = 1
        state.list = []
        state.scrollbarTop = 0
        state.active = null
      }
      const res = await get_chatting_user_list({pageNum: state.pageNum, pageSize: state.pageSize})
      res.data.list.forEach(item => {
        if(item.message) {
          item.message.createTimeAt = formatDate(item.message.createTime)
        }
      })
      commit("SET_CONVERSATION", res.data)
      return res
    },

    async setActive({commit, state, dispatch}, item) {
      if(item.id) {
        const conversations = state.list.find(el => el.id == item.id)
        if(conversations) {
          commit('SET_ACTIVE', conversations.id)
        }else {
          // 添加会话
          const res = await dispatch("addConversationPrivateMessage", {msgConversationId: item.id, push:true})
          commit('SET_ACTIVE', res.data.id)
        }
      }
    },

    /**
     * 初始化数据,更新会话列表
     * @param message 确认消息
     */
    updateConversationPrivateMessage({commit, state, dispatch}, message) {
      // 收到的信息在当前的会话列表
      const flag = state.list.some(item => item.id == message.msgConversationId)
      if(flag) {
        // 发信息更新会话列表位置移动到顶部
        commit("UPDATE_CONVERSATION_PRIVATE_MESSAGE", message)
      }else {
        // 添加新的会话列表
        dispatch('addConversationPrivateMessage', message)
      }
    },
    /**
     * 消息不在会话列表中添加新的消息列表
     * @param commit
     * @param message
     * @returns {Promise<void>}
     */
    async addConversationPrivateMessage({commit},message) {
      const res = await get_singleton_chatting_user({conversationId :message.msgConversationId})
      if(res.code === 100000) {
        commit("ADD_CONVERSATION_PRIVATE_MESSAGE", {data: res.data, push: message.push})
        return res
      }
    },
    closeMessage({commit}){
      commit("CLOSE_MESSAGE")
    },
    /**
     * 获取已读数量
     * @param commit
     */
    getCountAllRead({commit}){
      count_all_un_read().then(res => {
        commit("UPDATE_COUNT_ALL_READ", res.data)
      })
    }
  }
}